package com.sxjh.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;


/**
 * 重写uri中包含/java的请求
 */
@Slf4j
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Component
public class RewritUriFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
        //
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String requestURI = request.getRequestURI();
//        MDC.put("RewritUriFilter======TRACE_ID", UUID.randomUUID().toString().replace("-", ""));
        //log.info("RewritUriFilter=====URL            : {}", request.getRequestURL().toString());
        //log.info("RewritUriFilter====HTTP Method    : {}", request.getMethod());
        //线上环境前端请求包含/java/的请求会在经过nginx时直接转发到java服务
        //由于测试环境没有在nginx中配置，故需要把url中/java/过滤掉才能向后转发
        if (requestURI.startsWith("/java/")) {
            String newURI = requestURI.replace("/java", "");
            req.getRequestDispatcher(newURI).forward(req, res);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
        //
    }
}